package com.lill.stock.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lill.common.component.model.P;
import com.lill.common.component.util.IdUtil;
import com.lill.product.model.ProductCarModel;
import com.lill.stock.model.StockRouteModel;
import com.lill.stock.service.IStockRouteService;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.lill.common.component.util.PageUtils;
import com.lill.common.component.util.Query;
import com.lill.common.component.util.R;
import com.lill.stock.model.StockRealModel;
import com.lill.stock.service.IStockRealService;
import com.lill.support.annotation.CurrentUser;
import com.lill.system.model.SysUserEntity;

/**
 * 实时库存Controller
 *
 * @author lill
 * @date 2021-09-25 11:41:47
 */
@RestController
@RequestMapping("stock/real")
public class StockRealController {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
    @Autowired
    private IStockRealService stockRealService;
    @Autowired
    private IStockRouteService stockRouteService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity user) {
    	params.put("companyId", user.getCompanyId());
    	params.put("branchId", user.getBranchId());
    	if(params.containsKey("StockTransfer")){
    		params.put("branchId", null);
    	}
        //查询列表数据
        Query query = new Query(params);

        List<StockRealModel> stockRealList = stockRealService.queryList(query);
        int total = stockRealService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(stockRealList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("stockreal:info")
    public R info(@PathVariable("id") String id) {
    	StockRealModel stockReal = stockRealService.queryObject(id);
        return R.ok().put("stockReal", stockReal);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody StockRealModel stockReal,@CurrentUser SysUserEntity user) {
        int result=stockRealService.save(stockReal);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 入库新增
     * @param stockReal
     * @return
     */
    @RequestMapping("/saveBatch")
    public R saveBatch(@RequestBody StockRealModel stockReal) {
        List<StockRealModel> list = stockReal.getProductList();
        if(CollectionUtils.isNotEmpty(list)){
            for (StockRealModel stockRealModel : list) {
                //修改调度数据
                StockRouteModel stockRoute = new StockRouteModel();
                stockRoute.setId(stockRealModel.getId());
                stockRoute.setStatus(0);
                stockRouteService.update(stockRoute);
                //新增库存数据
                stockRealModel.setStorageId(stockReal.getStorageId());
                stockRealModel.setInnerDetailId(stockRealModel.getId());
                stockRealModel.setId(IdUtil.createIdbyUUID());
                stockRealModel.setInnerDate(new Date());
                stockRealModel.setState(1);
                stockRealModel.setTopClassifyId(ProductCarModel.classify);
            }
            int result=stockRealService.saveBatch(list);
            if(result>0){
                return R.ok();
            }else{
                return R.failure();
            }
        }
        return R.error("新增数据不能为空");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("stockreal:update")
    public R update(@RequestBody StockRealModel stockReal,@CurrentUser SysUserEntity user) {
        int result=stockRealService.update(stockReal);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }
    
    
    @RequestMapping("/import")
    public R importData(@RequestParam MultipartFile file,@CurrentUser SysUserEntity user) {
    	P result=P.ok();
    	try {
			Map<String, Object> baseMap=new HashMap<String, Object>();
			baseMap.put("company_id", user.getCompanyId());
			baseMap.put("branch_id", user.getBranchId());
			baseMap.put("person_id", user.getPersonId());
			baseMap.put("create_user", user.getId());
			baseMap.put("create_time", new Date());
			boolean xlsxFormat=false;
			if(file.getOriginalFilename().endsWith("xlsx")||file.getOriginalFilename().endsWith("XLSX")){
				xlsxFormat=true;
			}
			result=stockRealService.importData(baseMap,"stock_real",file.getInputStream(),xlsxFormat);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
    	if(result.isR()){
    		return R.ok();
    	}else{
    		return R.failure();
    	}
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("stockreal:delete")
    public R delete(@RequestBody String[] ids,@CurrentUser SysUserEntity user) {
    	Map<String, Object> params=new HashMap<String, Object>();
    	params.put("ids", ids);
        int result=stockRealService.deleteLogicByMap(params);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }
    
    @RequestMapping("/sale")
    public R sale(@RequestBody String[] ids,@CurrentUser SysUserEntity user) {
    	int result=stockRealService.saleRealStock(ids,user.getId());
    	if(result>0){
    		return R.ok();
    	}else{
    		return R.failure();
    	}
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {
        List<StockRealModel> list = stockRealService.queryList(params);
        return R.ok().put("list", list);
    }
    
    @RequestMapping("/stat")
    public R statStck(@CurrentUser SysUserEntity user) {
    	Map<String, Object> params=new HashMap<String, Object>();
    	params.put("companyId", user.getCompanyId());
    	params.put("branchId", user.getBranchId());
    	Map<String, Object> resultMap = stockRealService.queryStatStock(params);
    	return R.ok().put("data", resultMap);
    }
}
